<?php

/*
 * Copyright (C) 2010 Emanuele Colonnelli <emanuele.colonnelli@phpstruct.org>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace org\phpstruct\core;

/**
 * Description of Config
 *
 * @author Emanuele Colonnelli <emanuele.colonnelli@phpstruct.org>
 */
final class Config {

    const CACHE_KEY = 'CONFIG_INI';

    public static function get($property){
        $parts = \explode('.', $property, 2);

        $cfg = self::getInifile();

        return $cfg[$parts[0]][$parts[1]];
    }

    private static function getInifile() {
        $path = sprintf('%s%s.phpstruct%sconf%sconfig.ini',
                        $_SERVER['DOCUMENT_ROOT'],
                        \DIRECTORY_SEPARATOR,
                        \DIRECTORY_SEPARATOR,
                        \DIRECTORY_SEPARATOR
        );

        if (\file_exists($path)) {

            $cache = CacheFactory::getInstance()->factory(CacheFactory::SESSION);

            $inifile = $cache->get($cache->getKey(self::CACHE_KEY));

            if (!is_array($inifile) || isset($_GET['cleanup'])) {

                $inifile = \parse_ini_file($path, true);

                $key = $cache->getKey(self::CACHE_KEY);

                $cache->set($key, $inifile);
            }

            return $inifile;
        } else {
            throw new \Exception(Error::E_CONF_FILENOTFOUND(), Error::E_CONF_FILENOTFOUND, null);
        }
    }

}

